package edu.berkeley.biocode.flickr;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.uploader.Uploader;
import edu.berkeley.biocode.utils.BareBonesBrowserLaunch;
import org.xml.sax.SAXException;

import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.prefs.Preferences;

/**
 * AuthorizeFlickrUpload is generic class to authorize flickr uploads.
 */
public class AuthorizeFlickrUpload {
    Flickr f;
    RequestContext requestContext;
    String frob = "";
    public String token = "";
    public String apiKey = "7b9b362c4249b8be92ccea602f5a1850";
    public String sharedSecret = "4659049922e5f50b";
    public Uploader up;
    public Auth auth = null;

    public AuthorizeFlickrUpload()  {

    }

    public void init() throws Exception, IOException, SAXException {
        f = new Flickr(
                apiKey,
                sharedSecret,
                new REST()
        );

        f.setSharedSecret(sharedSecret);

        Flickr.debugStream = false;
        requestContext = RequestContext.getRequestContext();
        requestContext.setSharedSecret(sharedSecret);
        auth = getAuth();

        if (auth == null) {
            throw new Exception();
        } else {
            // Perform authorization
            try {
                requestContext.setAuth(auth);

                System.out.println("Authentication success");
                // This token can be used until the user revokes it.
                System.out.println("Token: " + auth.getToken());
                System.out.println("nsid: " + auth.getUser().getId());
                System.out.println("Realname: " + auth.getUser().getRealName());
                //System.out.println("Username: " + auth.getUser().getUsername());
                //System.out.println("Permission: " + auth.getPermission().getType());
                
                up = new Uploader(apiKey, sharedSecret);
                up = f.getUploader();

            } catch (Exception e) {
                System.out.println("Authentication failed");
                e.printStackTrace();
            }
        }
    }

    public Auth getAuth() throws Exception, SAXException, ParserConfigurationException {
        final Preferences prefs = Preferences.userRoot().node(System.getProperty("app.bioValidatorUserPreferences"));
        Auth auth = null;
        AuthInterface authInterface = f.getAuthInterface();

        try {
                frob = authInterface.getFrob();
        } catch (FlickrException e) {
            System.out.println("Flickr Exception encountered");
            e.printStackTrace();
            return null;
        }   catch (UnknownHostException e) {
            System.out.println("cannot contact Flickr.  Internet OK?");
            return null;
        }

        // Attempt to get a token from our preferences
        String token = prefs.get("FlickrToken", null);

        // no token, need to fetch it
        if (token == null) {
            System.out.println("token is null, initiate fetcherator");
            URL url = authInterface.buildAuthenticationUrl(Permission.WRITE, frob);
            //System.out.println("Press return after you are granted access at this URL:");
            //System.out.println(url.toExternalForm());
            BareBonesBrowserLaunch browser = new BareBonesBrowserLaunch();
            browser.openURL(url.toExternalForm());
            JOptionPane.showMessageDialog(new Frame(), "Press OK, after you grant Flickr Access\n(bioValidator should have opened a browser for you)");
//            BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));

            //String line = infile.readLine();

            try {
                auth = authInterface.getToken(frob);

            } catch (FlickrException e) {

                e.printStackTrace();
                return auth;
            }
            prefs.put("FlickrToken", auth.getToken());
            System.out.println(auth.getToken());

            // token found
            // TODO: catch case where token has been revoked
        } else {
            try {
                System.out.println("reading token from system preferences!");
                auth = authInterface.checkToken(token);
            } catch (FlickrException e) {
                prefs.remove("FlickrToken");
                e.printStackTrace();
                AuthorizeFlickrUpload a = new AuthorizeFlickrUpload();
                a.init();

                return null;
            }
        }
        return auth;
    }

    public static void main(String[] args) {
        try {
            AuthorizeFlickrUpload t = new AuthorizeFlickrUpload();

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}
